package com.youdianstar.app.support.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.youdianstar.app.api.ApiService
import com.youdianstar.app.common.PAGE_SIZE
import com.youdianstar.app.entity.OrderInfo
import com.youdianstar.app.common.event.NetEventLiveData
import java.io.IOException


/**
 * File: OrderPagingSource
 * Author: 82149 Create: 2021/11/11 18:34
 * Changes (from 2021/11/11)
 * --------------------------------------------------
 * description: 订单列表 paging3分页实现
 * ---------------------------------------------------
 *
 */
class OrderPagingSource(private val service: ApiService, private val eventLiveData: NetEventLiveData?=null) : PagingSource<Int, Any>(){

    //实现必须定义如何从已加载分页数据的中间恢复刷新,使用 state.anchorPosition 作为最近访问的索引来映射正确的初始键。
    //高级用法
    override fun getRefreshKey(state: PagingState<Int, Any>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Any> {
        //分页请求是按 offset/偏移量 决定的,所以key值内容不是页码Page,是当前数据下标index
        val index = params.key ?: 0 //当前数据下标,从0开始
        try {
            val result = service.getOrderRecord(index)
            result.data?.let { datas ->
                datas.forEach { ent->
                    // 如果是OrderInfo类型，设置pageType
                    if (ent is OrderInfo) {
                        ent.pageType = 0
                    }
                }
            }
            val dataSize :Int = if (null == result.data) 0 else result.data!!.size
//            val preKey = if (index > 0) index - PAGE_SIZE else null
            if (index==0 && dataSize==0){
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_EMPTY)
            } else{
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_OK)
            }
            return LoadResult.Page(
                //当前页加载的数据
                result.data!!,
                // 往上加载的Key ,如果不可以往上加载就null
                prevKey = null,
                // 加载下一页的key 如果传null就说明到底了
                nextKey = (if (dataSize<PAGE_SIZE) null else dataSize + index))
        } catch (e: IOException) {
            if (index==0)
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_ERROR)
            return LoadResult.Error(e)
        } catch (e: Exception) {
            eventLiveData?.postValue(NetEventLiveData.Result.NET_ERROR)
//            e.printStackTrace()
            return LoadResult.Error(e)
        }

    }
}